import { Injectable } from '@nestjs/common';
import { InjectRepository } from '@nestjs/typeorm';
import { Equal, Repository } from 'typeorm';
import { CreateFarmDto } from './dto/create-farm.dto';
import { UpdateFarmDto } from './dto/update-farm.dto';
import { Farm } from './entities/farm.entity';

@Injectable()
export class FarmService {
  constructor(
    @InjectRepository(Farm)
    private readonly farmRepository: Repository<Farm>
  ) {}

  create(createFarmDto: CreateFarmDto) {
    return 'This action adds a new farm';
  }

  findAll() {
    return this.farmRepository.find({
      where: {
        hasGbId: true
      }
    });
  }

  findByRegion(regionCode: string): Promise<Farm[]> {
    return this.farmRepository.findBy({
      regionCode: Equal(regionCode),
      hasGbId: false
    });
  }

  async findGbIdSequence(regionCode: string) {
    const maxSeq = await this.farmRepository.findOne({
      where: {
        regionCode: regionCode
      },
      order: {
        seq: 'DESC'
      }
    });
    let seq = 1;

    if (maxSeq !== null && maxSeq.seq !== null) {
      seq += maxSeq.seq;
    }
    return seq;
  }

  findOne(id: number) {
    return `This action returns a #${id} farm`;
  }

  update(id: number, updateFarmDto: UpdateFarmDto) {
    this.farmRepository.update(id, {
      hasGbId: true,
      seq: updateFarmDto.seq,
      gbIdStart: updateFarmDto.gbIdStart,
      province: updateFarmDto.province,
      city: updateFarmDto.city,
      distinct: updateFarmDto.distinct,
      industry: updateFarmDto.industry,
      encodeType: updateFarmDto.encodeType,
      networkIdentifier: updateFarmDto.networkIdentifier
    });
    return `This action updates a #${id} farm`;
  }

  remove(id: number) {
    return `This action removes a #${id} farm`;
  }
}
